package com.tanhua.manage.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.tanhua.manage.domain.Admin;
import com.tanhua.manage.interceptor.AdminHolder;
import com.tanhua.manage.service.AdminService;
import com.tanhua.manage.vo.AdminVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
public class AdminController {
    @Autowired
    private AdminService adminService;
    /**
     * 接口名称：用户登录验证码图片
     * 接口路径：GET/system/users/verification
     */
    @GetMapping("verification")
    public void verification(String uuid, HttpServletResponse response) throws IOException {
        // 通过验证码的工具类，生成验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(299, 99);
        String code = circleCaptcha.getCode();
        // 保存验证码到redis中
        adminService.saveCap(uuid,code);
        // 输出验证码
        circleCaptcha.write(response.getOutputStream());
    }

    /**
     * 接口名称：用户登录
     * 接口路径：POST/system/users/login
     */
    @PostMapping("login")
    public ResponseEntity<Object> login(@RequestBody Map<String,String> paramMap){
        return adminService.login(paramMap);
    }

    /**
     * 接口名称：用户基本信息
     * 接口路径：POST/system/users/profile
     */
    @PostMapping("profile")
    public ResponseEntity<Object> findUserInfo(){
        // 解析token获取对象
        Admin admin = AdminHolder.getAdmin();
        // 封装vo并返回
        AdminVo adminVo = new AdminVo();
        BeanUtils.copyProperties(admin,adminVo);
        return ResponseEntity.ok(adminVo);
    }

    /**
     * 接口名称：用户登出
     * 接口路径：POST/system/users/logout
     */
    @PostMapping("logout")
    public ResponseEntity<Object> logout(@RequestHeader("Authorization") String token)  {
        token = token.replace("Bearer ","");
        return adminService.logout(token);
    }
}
